package servlet;

import bean.Attence;
import bean.Student;
import utils.DBUtil;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

@WebServlet("/add")
public class AddServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ArrayList<Student> list = new ArrayList<>();
        request.setCharacterEncoding("utf-8");
        String sql = "select * from student";
        ResultSet rs = DBUtil.query(sql);
        try {
            while (rs.next()){
                int sid = rs.getInt("sid");
                String sname = rs.getString("sname");
                Student stu = new Student(sid, sname);
                list.add(stu);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        request.setAttribute("list",list);
        request.getRequestDispatcher("/WEB-INF/add.jsp").forward(request,response);

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");

        String sid = request.getParameter("sid");
        String time = request.getParameter("time");
        String type = request.getParameter("type");

        String sql = "insert into attence values(?,?,?,?)";
        int i = DBUtil.update(sql, null, time, type, sid);

        if(i>0){
            request.setAttribute("msg","添加成功");
            request.getRequestDispatcher("/WEB-INF/msg.jsp").forward(request,response);
        }else{
            request.setAttribute("msg","添加失败");
        }
    }
}
